import { Injectable } from '@nestjs/common';
import { CreateCateDto } from './dto/create-cate.dto';
import { UpdateCateDto } from './dto/update-cate.dto';
import { CateEntity } from './entities/cate.entity';
import { Repository } from 'typeorm';
import { InjectRepository } from '@nestjs/typeorm';

@Injectable()
export class CateService {
  // 使用InjectRepository装饰器并引入Repository这样就可以使用typeorm的操作了
  constructor(
    @InjectRepository(CateEntity)
    private readonly cateRepository: Repository<CateEntity>,
  ) {}

  create(createCateDto: CreateCateDto) {
    return 'This action adds a new cate';
  }

  async findAll(
    pageNum: number,
    pageSize: number,
  ): Promise<{
    code: number;
    data: CateEntity[];
    total: number;
  }> {
    const startIndex = (pageNum - 1) * pageSize;
    pageSize = typeof pageSize === 'string' ? parseInt(pageSize) : pageSize;
    const data = await this.cateRepository.query(
      'SELECT * FROM book_cate LIMIT ? OFFSET ?',
      [pageSize, startIndex],
    );
    const total = data.length; // 假设这里的 total 是数据长度，你可以根据实际情况计算
    const code = 200; // 假设这里的 code 是状态码，你可以根据实际情况设置
    return { code, data, total };
  }

  async findOne(
    cid: number,
    pageNum: number,
    pageSize: number,
  ): Promise<{ code: number; data: CateEntity[]; total: number }> {
    const startIndex = (pageNum - 1) * pageSize;
    pageSize = typeof pageSize === 'string' ? parseInt(pageSize) : pageSize;
    const data = await this.cateRepository.query(
      'SELECT * FROM book_cate WHERE id = ? LIMIT ? OFFSET ?',
      [cid, pageSize, startIndex],
    );
    const total = data.length; // 这里假设直接返回的 data 数组长度即为总数
    const code = 200;
    return { code, data, total };
  }

  update(id: number, updateCateDto: UpdateCateDto) {
    return `This action updates a #${id} cate`;
  }

  remove(id: number) {
    return `This action removes a #${id} cate`;
  }
}
